import React, {Component} from "react";
import {Affix, Menu, Breadcrumb, message, Icon, Row, Col, Button,Select} from "antd";
const Option = Select.Option;
import {Link} from "react-router";
import auth from "../common/auth";
import UpdatePwdModal from "../components/infoadmin/updatepwdmodal";
const SubMenu = Menu.SubMenu;
/**
 let funcData = [{
     id: "sub1", funcname: "菜单", icon: "appstore-o", link: "",
     children: [{key: "sub1-1", title: "HOME", icon: "file", link: "/admin/home"}]
 }, {
     id: "sub2", funcname: "站点管理", icon: "appstore-o", link: "",
     children: [
         {id: "sub2-1", funcname: "站点列表", icon: "file", link: "/admin/sitelist"},
         {id: "sub2-2", funcname: "栏目管理", icon: "file", link: "/admin/catalogpanel"},
         {id: "sub2-3", funcname: "模版管理", icon: "file", link: "/admin/home"}
     ]
 }, {
     id: "sub3", funcname: "内容管理", icon: "appstore-o", link: "",
     children: [
         {id: "sub3-1", funcname: "文档管理", icon: "file", link: "/admin/articlepanel"},
     ]
 }, {
     id: "sub4", title: "系统管理", icon: "appstore-o", link: "",
     children: [
         {id: "sub4-1", funcname: "用户管理", icon: "file", link: "/admin/userlist"},
         {id: "sub4-2", funcname: "菜单管理", icon: "file", link: "/admin/funclist"},
         {id: "sub4-3", funcname: "角色管理", icon: "file", link: "/admin/rolelist"},
     ]
 },{
     key: "sub5", funcname: "媒体库", icon: "appstore-o", link: "",
     children: [
         {id: "sub5-1", funcname: "图片库", icon: "file", link: "/admin/userlist"},
         {id: "sub5-2", funcname: "附件库", icon: "file", link: "/admin/funclist"},
     ]
 }];
**/
export default class App extends Component {
    //noinspection JSAnnotator  React.PropTypes.object.isRequired
    contextTypes: {
        router:React.prototype.object.isRequired
    }
    state = {
        funcData:[],
        passVisible: false,
        selectedMenu: {
            key: '',
            link: '',
            name: '',
        },
        sitelist:[],
        siteid:'',
        current: '',
        pwdVisible: false,
        defaultOpenKeys: [],
        openKeys:[]
    }

    showPassModal() {
        this.setState({
            passVisible: true
        })
    }

    closePassModal(params) {
        this.setState({
            passVisible: params.visible
        })
    }

    showPwdModal() {
        this.setState({
            pwdVisible: true
        });
    }

    closePwdModal() {
        this.setState({
            pwdVisible: false
        });
    }

    handleSiteChange(siteid){
      this.setState({siteid});
    }

    site_fetch(){
      auth.fetch('/sys/site/findAuthList',{},(res)=>{
        if(res.result == "0"){
          this.setState({
            sitelist:res.data,
            siteid:res.data[0].id
          });
        }
      })
    }

    func_fetch(params = {}){
      auth.fetch('/sys/func/thisFuncListByUser',{},(res)=>{
        if(res.result == "0"){
          this.setState({
            funcData:res.data.func
          });
        }
      })
    }

    handleLogout() {
        auth.fetch('/logout', {}, (data)=> {
            if (data.result == '0') {
                message.success('成功退出系统！');
                localStorage.token = "";
                //返回到主页面
                //this.context.router.push("/pension/admin");
                location = "/admin"
            } else {
                message.error(data.msg);
                localStorage.token = "";
                location = "/admin"
            }
        });
    }

    handleClick(e) {
        window.scrollTo(0, 0);
        this.setState({
            current: e.key
        });
        message.destroy();
    }
    openMenuChange(openKeysnow) {
        const openkeysbefore= this.state.openKeys;
        const latestOpenKey = openKeysnow.find(key => !(openkeysbefore.indexOf(key) > -1));
        const latestCloseKey = openkeysbefore.find(key => !(openKeysnow.indexOf(key) > -1));

        let nextOpenKeys = [];
        if (latestOpenKey) {
          nextOpenKeys = this.getAncestorKeys(latestOpenKey).concat(latestOpenKey);
        }
        if (latestCloseKey) {
          nextOpenKeys = this.getAncestorKeys(latestCloseKey);
        }

        let optParent=false;
        this.state.funcData.map((item)=>{
             if("menu_"+item.id ==nextOpenKeys){
                 optParent =true;
              }     
        })
        if (optParent) {
          this.setState({openKeys:nextOpenKeys});  
        }else{
           this.setState({openKeys:openKeysnow}); 
        }
       
      }
  getAncestorKeys(key) {
    const map = {
      sub3: ['sub2'],
    };
    return map[key] || [];
  }
    linkRendefFn(href, name, paths) {
      console.log(href, name, paths);
      if(href.path.indexOf("/")!=-1){
        return <a href={'http://localhost:3001' + href.path}>{href.breadcrumbName}</a>
      }else{
        return href.breadcrumbName;
      }

        //return <a href={'http://localhost:3000' + href}>{name.props.children}</a>
    }

    componentWillMount() {
      this.func_fetch()
      //this.setState({funcData:funcData})
    }

    render() {
        let menus = [];
        let openkeys = [];
        let url = location.href
        const loop = data => data.map((item) => {
            if (item.children != undefined && item.children.length > 0) {
                if(item.parentid==0){
                   menus.push(<SubMenu key={"menu_"+item.id} title={<span><Icon type={item.icon} />{item.funcname}</span>}>{loop(item.children)}</SubMenu>);       
                  // openkeys.push("menu_"+item.id);
                 }else{
                   return <SubMenu key={"menu_"+item.id} title={<span>{item.funcname}</span>}>{loop(item.children)}</SubMenu>
                 }
               if (this.state.current == "") {
                    this.state.current = "menu_"+item.id;
                    }

            } else {
                if (url.indexOf(item.url) != -1) {
                    this.state.current = "menu_"+item.id;
                }
                return <Menu.Item key={"menu_"+item.id}  ><Link to={item.url} >{item.funcname}</Link></Menu.Item>;
            }
        });
        loop(this.state.funcData);
       // if (this.state.openkeys.length == 0) {
           // this.state.openkeys = openkeys;
      //  }
        //const context = this.props.children ==null ?  <DatePanel/> :this.props.children;
        const context = this.props.children;
        //const breadcrumb = [{path:"/pension/admin/home",breadcrumbName:"首页"}];
        //let bg =this.props.children.props.location.pathname.indexOf('scalelist')!=-1 ? {backgroundColor:'#212737'}:{};
        //let hbg =this.props.children.props.location.pathname.indexOf('scalelist')!=-1 ? {backgroundColor:'#272c3F'}:{};
        //  let bg ={backgroundColor:'#212737'};
        //  let hbg ={backgroundColor:'#272c3F'};
        let siteOptions =[];
        if(this.state.sitelist.length>0){
          const loop = data => data.map((site) => {
            return <Option key={site.id}>{site.name}</Option>;
          });
          siteOptions = loop(this.state.sitelist);
        }

        return (
            <div className="layout-aside">
             
                <aside className="layout-sider">
                    <Affix offsetTop={0}>
                     <div className="layout-logo"></div>
                      <Menu mode="inline" onClick={this.handleClick.bind(this)} defaultSelectedKeys={[this.state.current]}
                            selectedKeys={[this.state.current]} openKeys={this.state.openKeys} onOpenChange={this.openMenuChange.bind(this)}>
                          {menus}
                      </Menu>
                    </Affix>
                </aside>
            

                <div className="layout-main">
                     <Affix offsetTop={0}>
                        <div className="layout-header">
                            <Row type="flex" style={{height: 50}} justify="space-around" align="middle">
                                <Col span="22">
                                    <div className="login_img float_left"></div>
                                </Col>
                                <Col span="1" className="text_right">
                                    <Button onClick={this.handleLogout.bind(this)} type="primary" size="small"
                                            shape="circle">
                                              <Icon type="poweroff" />
                                    </Button>
                                </Col>
                                <Col span="1" className="text_right">
                                    <Button onClick={this.showPwdModal.bind(this)} type="primary" size="small"
                                            shape="circle">
                                             <Icon type="unlock" />
                                    </Button>
                                    <UpdatePwdModal visible={this.state.pwdVisible} callbackParent={this.closePwdModal.bind(this)}/>
                                </Col>
                            </Row>
                        </div>
                        <div className="layout-breadcrumb">
                            <Breadcrumb {...this.props} itemRender={this.linkRendefFn.bind(this)}/>
                        </div>
                    </Affix>
                   

                    
                    <div className="layout-container">
                        <div className="layout-content">
                            {context }
                        </div>

                    </div>
                </div>
            </div>
        )
    }
};
